var fs = require('fs');


let findPromise = function () {
  let p = new Promise((resolve, reject) => {
    fs.readFile('./db.json', function (err, data) {
      if (err) {
        reject(err);
      } else {
        let res = JSON.parse(data);
        let {students} = res;
        resolve(students);
      }
    });
  });

  return p;
};

let writePromise = function (data) {
  let p = new Promise((resolve, reject) => {
    fs.writeFile('./db.json', data, function (err, data) {
      if (err) {
        reject(err);
      } else {
        
      }
    });
  });

  return p;
};

//使用promise实现读文件的异步操作,可以用来读取接口之类的

exports.add = function (student) {
  findPromise().then((res) => {

    // let stu = res.find(item => item.id === id);

    res.push(student);

    writePromise(JSON.stringify({
      students: res
    }));


  });
};

exports.deleteById = function (id) {
  findPromise().then((res) => {
    // res.map((item) => {
    //   console.log(item);
    // });
    let deleteId = res.findIndex(item => item.id === id);

    console.log(333, deleteId);

    if (deleteId !== -1) {
      res.splice(deleteId, 1);
    }

    writePromise(JSON.stringify({
      students: res
    }));
  });
};

exports.update = function (student) {
  findPromise().then((res) => {

    let stu = res.find(item => item.id = student.id);

    //通过浅拷贝修改res的stu的值
    for (var key in student) {
      stu[key] = student[key];
    }

    writePromise(JSON.stringify({
      students: res
    }));


  });
};

exports.findById = function (id) {
  findPromise().then((res) => {
    // res.map((item) => {
    //   console.log(item);
    // });
    let stu = res.find(item => item.id === id);

    console.log(stu);
  });
};
